package com.gj.jedis;
import redis.clients.jedis.Jedis;
import java.util.Random;

public class PhoneCode {
    public static void main(String[] args) {
        //模拟验证码发送
        verifyCode("15425648235");
        getRedisCode("15425648235","960253");
    }
    //生成6位验证码
    public static String getCode(){
        Random random = new Random();
        String code="";
        for (int i = 0; i < 6; i++) {
            int rand = random.nextInt(10);
            code+=rand;
        }
        return code;
    }
    //校验验证码
    public static void getRedisCode(String phone,String code){
        //从redis获取验证码
        Jedis jedis = new Jedis("192.168.200.130",6379);
        String codeKey="VerifyCode"+phone+":code";
        String redisCode = jedis.get(codeKey);
        if(redisCode.equals(code)){
            System.out.println("成功");
        }else {
            System.out.println("失败");
        }
        jedis.close();
    }
    //验证码放到redis，让每个用户每天只能发送三次
    public static void verifyCode(String phone){
        Jedis jedis = new Jedis("192.168.200.130",6379);
        //拼接key
        //手机发送次数key
        String countKey="VerifyCode"+phone+":count";
        //验证码key
        String codeKey="VerifyCode"+phone+":code";
        //每个用户每天只能发送三次
        String count = jedis.get(countKey);
        if(count==null){
            //第一次发,set键值对
            jedis.setex(countKey,24*60*60,"1");//key是countKey，过期时间一天，值是1，代表这个用户只发过一次
        } else if (Integer.parseInt(count)<=2) {
            //不是第一次，发送次数+1
            jedis.incr(countKey);
        } else if (Integer.parseInt(count)>2) {
            //发送三次，不能再发送
            System.out.println("今天您已发送超过三次验证码，不能再发送了");
            jedis.close();
        }
        //生成的验证码需要放到redis
        String vcode = getCode();
        jedis.setex(codeKey,120,vcode);
        jedis.close();
    }
}
